package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Brand;
import com.itheima.pojo.pagebean;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceimpl;
import com.sun.media.sound.SoftAudioPusher;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/brand/*")

public class brandservlet extends Baseservlet{
    private BrandService brandService = new BrandServiceimpl();
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader bufferedReader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();
        System.out.println(json + "json");

        Brand brand = JSON.parseObject(json, Brand.class);
        brandService.add(brand);
        System.out.println(brand + "brand");
        resp.getWriter().write("success");
    }

    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Brand> brands = brandService.selectAll(); // 修改这里
        String json = JSON.toJSONString(brands);

        resp.setContentType("application/json;charset=utf-8"); // 修正 MIME 类型
        resp.getWriter().write(json);
    }

    public void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BufferedReader bufferedReader = req.getReader();
    String json = bufferedReader.readLine();

    // 解析 JSON 对象，获取 ids 数组
    JSONObject jsonObject = JSON.parseObject(json);
    JSONArray jsonArray = jsonObject.getJSONArray("ids");

    // 将 JSONArray 转换为 List<Integer>
    List<Integer> idList = jsonArray.toJavaList(Integer.class);

    // 将 List<Integer> 转换为 int[]
    int[] ids = idList.stream().mapToInt(Integer::intValue).toArray();

    brandService.deleteByIds(ids);
    resp.getWriter().write("success");
}


    public void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String _currentPage = req.getParameter("currentPage");
        String _pageSize = req.getParameter("pageSize");

        // 去除字符串中的空白字符
        _currentPage = _currentPage.trim();
        _pageSize = _pageSize.trim();

        // 检查参数是否为空，并设置默认值
        int currentPage;
        int pageSize;
        try {
            currentPage = Integer.parseInt(_currentPage);
            pageSize = Integer.parseInt(_pageSize);
        } catch (NumberFormatException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("Invalid parameter: currentPage or pageSize must be a valid integer.");
            return;
        }

        pagebean<Brand> pagebean = brandService.selectByPage(currentPage, pageSize);
        String json = JSON.toJSONString(pagebean);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(json);
    }



    public void selectByPageandCondition(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String currentPageStr = req.getParameter("currentPage");
        String pageSizeStr = req.getParameter("pageSize");

        if (currentPageStr == null || currentPageStr.isEmpty()) {
            currentPageStr = "1"; // 默认值
        }

        if (pageSizeStr == null || pageSizeStr.isEmpty()) {
            pageSizeStr = "10"; // 默认值
        }

        int currentPage;
        int pageSize;

        try {
            currentPage = Integer.parseInt(currentPageStr);
            pageSize = Integer.parseInt(pageSizeStr);
        } catch (NumberFormatException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("Invalid parameter: currentPage or pageSize must be a valid integer.");
            return;
        }

        String json = req.getReader().readLine();
        Brand brand = JSON.parseObject(json, Brand.class);

        if (brand == null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("Invalid JSON data.");
            return;
        }

        System.out.println("Received brand condition: " + brand);
        System.out.println("Current Page: " + currentPage + ", Page Size: " + pageSize);

        try {
            pagebean<Brand> pageBean = brandService.selectByPageandCondition(currentPage, pageSize, brand);
            String json1 = JSON.toJSONString(pageBean);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(json1);
            resp.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("An error occurred while processing the request.");
        }
    }

}
